package org.developerworks.baseball.desktop;

import java.util.List;
import java.util.Properties;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.developerworks.baseball.Player;

public class Main {
    
    //http://www.slideshare.net/ssakpi/java-persistence-api-jpa-basics
    
    private static EntityManager entityManager;
    private static EntityManagerFactory entityManagerFactory;
    private static List<Player> players;
    public static void main(String[] args) {

	entityManagerFactory = Persistence
		.createEntityManagerFactory("Baseball");
	// or use
	// entityManagerFactory =
	// Persistence
	// .createEntityManagerFactory("Baseball",setProperties());
	
	entityManager = entityManagerFactory.createEntityManager();
	Player player = new  Player();
	
	printPlayers();
	
	
	System.out.println("add player");
	
	player.setFirstName("aaa");
	player.setLastName("mmm");
	persistPlayer(player);
	printPlayers();
	
	System.out.println("delete player");
	deletePlayer(player);
	printPlayers();
	
	System.out.println("update player");
	player.setId(6);
	player.setFirstName("Birduk");
	player.setLastName("Valerii");
	updatePlayer(player);
	
	printPlayers();
	

    }
    private static List<Player> seletPlayers(){
	return entityManager.createQuery(
		"select p from Player p").getResultList();
    }
    
    private static void updatePlayer(Player player){
	entityManager.getTransaction().begin();
	entityManager.merge(player);
	entityManager.getTransaction().commit();
	
    }
    private static void deletePlayer(Player player){
	entityManager.getTransaction().begin();
	entityManager.remove(player);
	entityManager.getTransaction().commit();	
    }
    private static void persistPlayer(Player player){
	
	entityManager.getTransaction().begin();
	entityManager.persist(player);
	entityManager.getTransaction().commit();
    }
    
    private static void printPlayers(){
	players = seletPlayers();
	printPlayers(players);
    }
    private static void printPlayers(List<Player> players){
	for (Player player : players) {
	   
	    System.out.print(player.getId());
	    System.out.print("\t");
	    System.out.print(player.getFirstName());
	    System.out.print("\t");
	    System.out.println(player.getLastName());
	    System.out.println("-----------------------------------------");
	}
    }

    private static Properties setProperties() {
	java.util.Properties properties = new java.util.Properties();
	properties.put("openjpa.ConnectionURL",
		"jdbc:mysql://localhost:3306/baseball");
	properties.put("openjpa.ConnectionDriverName", "com.mysql.jdbc.Driver");
	properties.put("openjpa.ConnectionUserName", "root");
	properties.put("openjpa.ConnectionPassword", "");
	properties.put("openjpa.jdbc.SynchronizeMappings", "buildSchema");
	return properties;
    }

}
